package com.jy.unkown;

import static android.content.Context.MODE_PRIVATE;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.jy.common.BaseApplication;
import com.jy.utils.AppGlobals;
import com.jy.utils.cache.CacheManager;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Properties;

public class UnkownTool {
    public static String getOaid() {
        try {
            SharedPreferences sharedPreferences = AppGlobals.getApplication().getSharedPreferences("pangle_com.byted.pangle_tt_ad_sdk_sp", Context.MODE_PRIVATE);
            String json = sharedPreferences.getString("sdk_app_log_oaid", "{}");
            JSONObject jsonObject = new JSONObject(json);
            String oaid = jsonObject.optString("value");
            if (!TextUtils.isEmpty(oaid)) {
                CacheManager.updateOaid(oaid);
                return oaid;
            }
        } catch (Exception exception) {

        }


        try {
            String path2[] = {"device_register_oaid_refine", "pangle_com.byted.pangle_device_register_oaid_refine"};
            for (int i = 0; i < path2.length; i++) {
                String name = path2[i];
                SharedPreferences sharedPreferences = AppGlobals.getApplication().getSharedPreferences(name, MODE_PRIVATE);
                if (sharedPreferences != null) {
                    String msg = sharedPreferences.getString("oaid", "");
                    if (!TextUtils.isEmpty(msg)) {
                        try {
                            JSONObject jsonObject = new JSONObject(msg);
                            String id = jsonObject.optString("id");
                            if (!TextUtils.isEmpty(id)) {
                                CacheManager.updateOaid(id);
                                return id;
                            }
                        } catch (Exception exception) {

                        }
                    }
                }

            }
        } catch (Exception exception) {

        }
        return "";
    }


    private static final String HARMONY_OS = "harmony";

    /**
     * check the system is harmony os
     *
     * @return true if it is harmony os
     */
    public static boolean isHarmonyOS() {
        try {
            Class clz = Class.forName("com.huawei.system.BuildEx");
            Method method = clz.getMethod("getOsBrand");
            return HARMONY_OS.equals(method.invoke(clz));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 判断是否鸿蒙系统
     *
     * @param context
     * @return
     */
    public static boolean isHarmony(Context context) {
        try {
            //判断是否存在鸿蒙系统的运行库，非Harmony系统或者EMUI系统的会找不到这个类而抛异常，
            //可以快速排除掉其他的Android系统
            Class<?> accountAbilityClass = Class.forName("ohos.aafwk.ability.Ability");

            //再判断是否有纯净模式的activity，来进一步区分是Harmony系统或者是EMUI系统
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setPackage("com.huawei.systemmanager");
            intent.setComponent(new ComponentName("com.huawei.systemmanager",
                    "com.huawei.systemmanager.puremode.PureModeActivity"));
            PackageManager packageManager = context.getPackageManager();
            List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            return list.size() > 0;

        } catch (Throwable e) {
            e.printStackTrace();
            return false;
        }
    }


    public static String hmsCore() {
        PackageInfo pkginfo = getPackageInfo(BaseApplication.getBaseApplication(), "com.huawei.hwid");
        if (pkginfo != null) {
            String hms_version = pkginfo.versionCode + "";
            return hms_version;
        }
        return null;
    }


    public static String huaweiMarketVersion() {
        PackageInfo pkginfo = getPackageInfo(BaseApplication.getBaseApplication(), "com.huawei.appmarket");
        if (pkginfo != null) {
            String hms_version = pkginfo.versionCode + "";
            return hms_version;
        }
        return null;
    }


    public static String getOppoMarketVersion() {
        PackageInfo pkginfo = getPackageInfo(BaseApplication.getBaseApplication(), "com.oppo.market");
        if (pkginfo==null){
            pkginfo=getPackageInfo(BaseApplication.getBaseApplication(), "com.heytap.market");
        }
        if (pkginfo != null) {
            String hms_version = pkginfo.versionCode + "";
            return hms_version;
        }

        return null;
    }

    public static String getVivoMarketVersion() {
        PackageInfo pkginfo = getPackageInfo(BaseApplication.getBaseApplication(), "com.bbk.appstore");
        if (pkginfo != null) {
            String hms_version = pkginfo.versionCode + "";
            return hms_version;
        }
        return null;
    }

    private static PackageInfo getPackageInfo(Context context, String pkgName) {
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(pkgName, PackageManager.GET_CONFIGURATIONS);
            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pi;
    }


    // 检测MIUI
    private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
    private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";
    static boolean isMiUI;
    static boolean isCHecked;

    public static boolean isMIUI() {
//        if(SPUtils.getInstance().getCacheDataSP().contains("isMIUI"))
//        {
//            return SPUtils.getInstance().getCacheDataSP().getBoolean("isMIUI",false);
//        }
        if (isCHecked) {
            return isMiUI;
        }
        Properties prop = new Properties();
        try {
            prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        isMiUI = prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
                || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
                || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null;
//        SPUtils.getInstance().putCacheData("isMIUI",isMIUI);//保存是否MIUI
        isCHecked = true;
        return isMiUI;
    }

    static String miuiVersion;

    public static String getMiuiVersion() {
        if (!TextUtils.isEmpty(miuiVersion)) {
            return miuiVersion;
        }
        miuiVersion = getSystemProperty("ro.miui.ui.version.name");
        return miuiVersion;
    }

    public static String getSystemProperty(String propName) {
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            Log.e("TAG", "Unable to read sysprop " + propName, ex);
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    Log.e("TAG", "Exception while closing InputStream", e);
                }
            }
        }
        return line;
    }

    public static String cellId() {
        if (ActivityCompat.checkSelfPermission(BaseApplication.getBaseApplication(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        TelephonyManager tel = (TelephonyManager) BaseApplication.getBaseApplication().getSystemService(Context.TELEPHONY_SERVICE);
        CellLocation cel = tel.getCellLocation();
//        int nPhoneType = tel.getPhoneType();
        //移动联通 GsmCellLocation
        if (cel instanceof GsmCellLocation) {
            GsmCellLocation gsmCellLocation = (GsmCellLocation) cel;
            int nGSMCID = gsmCellLocation.getCid();
            if (nGSMCID > 0) {
                if (nGSMCID != 65535) {
                    return Integer.toString(nGSMCID);
                }
            }
        } else if (cel instanceof CdmaCellLocation) {
            return Integer.toString(((CdmaCellLocation) cel).getBaseStationId());
        }
        return null;
    }


    public static String getNetworkTypeStr() {
        try {
            //获取系统的网络服务
            ConnectivityManager connManager = (ConnectivityManager) AppGlobals.getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
            //如果当前没有网络
            if (null == connManager)
                return "Unknown";
            //获取当前网络类型，如果为空，返回无网络
            NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
            if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
                return "Unknown";
            }
            // 判断是不是连接的是不是wifi
            NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (null != wifiInfo) {
                NetworkInfo.State state = wifiInfo.getState();
                if (null != state)
                    if (state == NetworkInfo.State.CONNECTED
                            || state == NetworkInfo.State.CONNECTING) {
                        return "Wi-Fi";
                    }
            }
            // 如果不是wifi，则判断当前连接的是运营商的哪种网络2g、3g、4g等
            NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (null != networkInfo) {
                NetworkInfo.State state = networkInfo.getState();
                String strSubTypeName = networkInfo.getSubtypeName();
                if (null != state)
                    if (state == NetworkInfo.State.CONNECTED
                            || state == NetworkInfo.State.CONNECTING) {
                        switch (activeNetInfo.getSubtype()) {
                            //如果是2g类型
                            case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2g
                            case TelephonyManager.NETWORK_TYPE_CDMA: // 电信2g
                            case TelephonyManager.NETWORK_TYPE_EDGE: // 移动2g
                            case TelephonyManager.NETWORK_TYPE_1xRTT:
                            case TelephonyManager.NETWORK_TYPE_IDEN:
                                return "2G";
                            //如果是3g类型
                            case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3g
                            case TelephonyManager.NETWORK_TYPE_UMTS:
                            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                            case TelephonyManager.NETWORK_TYPE_HSDPA:
                            case TelephonyManager.NETWORK_TYPE_HSUPA:
                            case TelephonyManager.NETWORK_TYPE_HSPA:
                            case TelephonyManager.NETWORK_TYPE_EVDO_B:
                            case TelephonyManager.NETWORK_TYPE_EHRPD:
                            case TelephonyManager.NETWORK_TYPE_HSPAP:
                                return "3G";
                            //如果是4g类型
                            case TelephonyManager.NETWORK_TYPE_LTE:
                                return "4G";
                            case 20:
                                return "5G";
                            default:
                                //中国移动 联通 电信 三种3G制式
                                if (strSubTypeName.equalsIgnoreCase("TD-SCDMA")
                                        || strSubTypeName.equalsIgnoreCase("WCDMA")
                                        || strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                                    return "3G";
                                } else {
                                    return "4G";
                                }
                        }
                    }
            }
            NetworkInfo EthernetInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
            if (null != EthernetInfo) {
                NetworkInfo.State state = EthernetInfo.getState();
                if (null != state)
                    if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                        return "4G";
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Unknown";
    }


    public static String getOperator() {
        Resources resources = BaseApplication.getBaseApplication().getResources();
        int mcc = resources.getConfiguration().mcc;
        int mnc = resources.getConfiguration().mnc;
        NetworkOperator operator = NetworkOperator.Companion.from(mcc * 100 + mnc);

        if (ActivityCompat.checkSelfPermission(BaseApplication.getBaseApplication(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return operator.getOpName();
        }

        TelephonyManager telephonyManager = ((TelephonyManager) BaseApplication.getBaseApplication().getSystemService(Context.TELEPHONY_SERVICE));
        String simOperator = telephonyManager.getSimOperator();

        operator = NetworkOperator.Companion.from(Integer.parseInt(simOperator));

        return operator.getOpName();
    }


}
